package org.batatasframework.strategy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import cn.bonoon.kernel.util.ItemSortable;
import cn.bonoon.kernel.util.MD5Util;

public abstract class AbstractServiceStrategyHandler extends ItemSortable implements ServerStrategyHandler{
	
	protected AbstractServiceStrategyHandler(String id, String name){
		this.id = id;
		this.name = name;
	}

	private StrategyRestraintChecker strategyRestraintChecker = new NullStrategyRestraintChecker();
	
	protected AbstractServiceStrategyHandler(){
		this.id = MD5Util.randomMD5String();
	}
	
	@Override
	public void setId(String id) {
		throw new RuntimeException("不允许对ID进行set值！");
	}
	
	public void setStrategyRestraintChecker(StrategyRestraintChecker strategyRestraintChecker) {
		if(null != strategyRestraintChecker){
			this.strategyRestraintChecker = strategyRestraintChecker;
		}
	}
	
	/** 允许子类进行初始化处理 */
	public void init() throws ServletException{}

	@Override
	public ServerStrategyResult execute(ServerStrategyEvent event)
			throws IOException, ServletException {
		ServerStrategyResult result = ServerStrategyResult.CONTINUE;
		if(strategyRestraintChecker.needRestraint(event)){
			result = internalExecute(event);
			
			if(result == ServerStrategyResult.RETURN){
				event.setRunable(false);
				HttpServletResponse response = event.getResponse();
				String deniedAccessHtml = generateDeniedAccessHtml(event);
				response.setContentType("text/html;charset=UTF-8");
				response.getWriter().write(deniedAccessHtml);
			}
		}
		return result;
	}
	
	protected String generateDeniedAccessHtml(ServerStrategyEvent event){ return ""; }
	
	protected abstract ServerStrategyResult internalExecute(ServerStrategyEvent event)
			throws IOException, ServletException;
	
//	
//	@Override
//	public int getOrdinal() {
//		return ordinal;
//	}
//	
//	public void setOrdinal(int ordinal) {
//		this.ordinal = ordinal;
//	}
//
//	@Override
//	public String getName() {
//		return name;
//	}
//
//	public String getId() {
//		return id;
//	}
}
